import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/blog_delete")
public class BlogDeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.先判定用户的登陆状态
        HttpSession session=req.getSession(false);
        if(session==null){
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("未登录，不能删除");
            return;
        }
        User user=(User) session.getAttribute("user");
        if(user==null){
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("未登录，不能删除");
            return;
        }
        //2.获取到blogId
        String blogId=req.getParameter("blogId");
        if(blogId==null){
            //blogId不存在，无法删除
            resp.setStatus(404);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("要删除的blogId有误");
            return;
        }
        //3.查询出这个blogId对应的blog对象
        BlogDao blogDao=new BlogDao();
        Blog  blog=blogDao.selectOne(Integer.parseInt(blogId));
        if(blog==null){
            //blogId不存在，无法删除
            resp.setStatus(404);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("要删除的blog不存在");
            return;
        }
        //4.判定登陆用户是否是文章作者
        if(blog.getUserId()==user.getUserId()){
            //blogId不存在，无法删除
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("无法删除别人的博客");
            return;
        }
        //5.执行删除操作
        blogDao.delete(Integer.parseInt(blogId));
        //6.返回302重定向
        resp.sendRedirect("blog_list.html");
    }
}
